package com.woniuxy.juc;

import lombok.Data;
import lombok.ToString;
import sun.misc.Unsafe;

import java.lang.reflect.Field;

/**
 * <P> @Author: ideaAdmin
 * <P> TODO: Class
 * <P> TODO: Unsafe 方法使用
 * <P> Date: 2022/4/10:9:59
 * <P> Description:
 */

public class UnsafeTest {
    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
        Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
       theUnsafe.setAccessible(true);
        Unsafe unsafe = (Unsafe) theUnsafe.get(null);
        System.out.println(unsafe);

        //TODO 1.获取域的偏移地址
        long idOffset = unsafe.objectFieldOffset(Teacher.class.getDeclaredField("id"));
        long nameOffset = unsafe.objectFieldOffset(Teacher.class.getDeclaredField("name"));

        //TODO 2.指向cas操作
        Teacher teacher = new Teacher();
        //TODO 对象 属性偏移地址 原来的值 新值
        unsafe.compareAndSwapInt(teacher,idOffset,0,10);
        unsafe.compareAndSwapObject(teacher,nameOffset,null,"123");

        System.out.println(teacher);
    }

    @Data
    @ToString
    static class Teacher{
        volatile int id;
        volatile String name;
    }
}
